from rest_framework import serializers
from app_student.models import Teacher, Student


# class StudentSerializer(serializers.ModelSerializer):
#     class Meta:
#         model = Student
#         fields = '__all__'  # 所有字段


# class TeacherSerializer(serializers.ModelSerializer):
# tname = serializers.CharField()
# student_list = serializers.ListField(write_only=True)  # 传过来的学生集合, 是一个列表
# student_set = StudentSerializer(many=True, read_only=True)

# json  =>  model   json中提供一个 student_list 字段,  创建老师的时候, 需要给老师添加的学生
# read_only   model  =>  json     返回的json中 有一个字段:student_set, 里面是学生的信息
#
# def create(self, validated_data):
#     # 1. 取出学生列表
#     student_list = validated_data.pop('student_list')  # [1,2,3]
#     teacher = Teacher.objects.create(**validated_data)  # validated_data =>  只有tname
#     teacher.student_set.add(*student_list)  # add(1,2)y   add([1,2,3]) x
#     return teacher

# class Meta:
#     model = Teacher
#     fields = '__all__'  # 所有字段


# 序列化,  数据转换
# 序列化数据    一串数据,   josn->  字符串,  序列化的数据
# 结构化数据    有结构的, 用字段来区分,  数据库中的 行, 就是结构化,  object 也是结构化的 , 因为object中有属性

# 序列化
# 把结构化, 变成序列化,  object  =>  json   =>   前端    读过程

# 反序列化
# 把序列化数据-> 结构化数据   json => object  =>  mysql   写过程

# 序列化器, 转换的过程, 需要根据序列化器中的字段的约束来转换

# 读过程:  需要什么字段
# 写过程:  需要什么字段

# class StudentSerializer(serializers.ModelSerializer):
# 根据模型生成序列化器的字段
#     class Meta:
#         model = Student
#         fields = '__all__'  # 所有字段

# class Student(models.Model):
#     sname = models.CharField('姓名', max_length=24)
#     teacher = models.ManyToManyField(Teacher)
#
#     class Meta:
#         db_table = 'tb_student'
#
#     def __str__(self):
#         return self.sname

class StudentSerializer(serializers.ModelSerializer):
    # sname = serializers.CharField(max_length=24)  # 读写都需要的字段
    # teacher = TeacherSerializer(many=True)

    class Meta:
        model = Student
        fields = '__all__'  # 所有字段
        # 读方向有 三个字段:  id, sname,  teacher(老师id列表)
        # 写方向有 两个字段: "sname",   "teacher": [](老师id列表)





# 有错就停
# def student_list_validator(data):
#     print(data)  # [1,2,3,4,5]
#     for sid in data:
#         try:
#             Student.objects.get(id=sid)
#         except Exception as e:
#             raise serializers.ValidationError('学生数据有误')
#     return data   # [1,2,3]

# 过滤有用数据, 继续
# def student_list_validator(data):
#     print(data)  # [1,2,3,4,5]
#     # validator_data = []
#     for sid in data[::-1]:
#         try:
#             Student.objects.get(id=sid)
#         except Exception as e:
#             data.remove(sid)  # 如要要修改数据, 只能修改原变量名
#             # raise serializers.ValidationError('学生数据有误')
#     # return validator_data   # [1,2,3]  # 不需要return
class TeacherStudentSerializer(serializers.ModelSerializer):
    class Meta:
        model = Student
        fields = ('id', 'sname')
        # fields = '__all__'  # 所有字段


class TeacherSerializer(serializers.ModelSerializer):
    # student_list = serializers.ListField(write_only=True, validators=[student_list_validator])
    student_list = serializers.ListField(write_only=True)  # {"student_list":[1,2,3,4]}
    # t = Teacher()
    # t.student_set.all()
    student = TeacherStudentSerializer(read_only=True, many=True)  # id列表[{id:1, sname:lisi},2,3,4,5]
    student_count = serializers.IntegerField(read_only=True)

    def validate_student_list(self, data):
        for sid in data[::-1]:
            try:
                Student.objects.get(id=sid)
            except Exception as e:
                data.remove(sid)  # 如要要修改数据, 只能修改原变量名
        return data

    def validate(self, attrs):
        print(attrs)
        return attrs

    class Meta:
        model = Teacher
        fields = '__all__'  # 所有字段
        # 读方向有三个字段: "id": 1,"tname": "老师1","active": true
        # 写方向有两个字段: "tname": "", "active": false

    def create(self, validated_data):
        student_list = validated_data.pop('student_list')
        obj = super().create(validated_data)
        obj.student_set.add(*student_list)
        return obj

#   写(json=>obj)                                                读(obj=>json)
#   json{"sname":"lxp"}=> 验证 => obj{sname:"lxp"}=>.save()       obj{sname:"lxp"}  =>  json{"sname":"lxp"}
